package tubesrus.servlets;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import tubesrus.beans.Utilisateur;
import tubesrus.beans.myStateless;




public class UploaderImage extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@EJB myStateless s;

	private static final String TMP_DIR_PATH = "../server/default/tmp";
	private File tmpDir;
	private static final String DESTINATION_DIR_PATH ="../server/default/data/Tubesrus";
	private File destinationDir;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		tmpDir = new File(TMP_DIR_PATH);
		if(!tmpDir.isDirectory()) {
			throw new ServletException(TMP_DIR_PATH + " is not a directory");
		}
		destinationDir = new File(DESTINATION_DIR_PATH);
		if(!destinationDir.isDirectory()) {
			throw new ServletException(DESTINATION_DIR_PATH+" is not a directory");
		}

	}


	public UploaderImage() {
		super();
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
		/*
		 *Set the size threshold, above which content will be stored on disk.
		 */
		fileItemFactory.setSizeThreshold(4*1024*1024); //4 MB
		/*
		 * Set the temporary directory to store the uploaded files of size above threshold.
		 */
		fileItemFactory.setRepository(tmpDir);

		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		try {
			/*
			 * Parse the request
			 */
			List<FileItem> items = uploadHandler.parseRequest(request);
			Iterator<FileItem> itr = items.iterator();
			while(itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				String dossier = "/images";
				/*
				 * Handle Form Fields.
				 */
				if(item.isFormField()) {
				} 
				else {
					//Handle Uploaded files.
					/*out.println("Field Name = "+item.getFieldName()+
						", File Name = "+item.getName()+
						", Content type = "+item.getContentType()+
						", File Size = "+item.getSize());
					/*
					 * Write file to the ultimate location.
					 */
					System.out.println("id = " +  ((Utilisateur)request.getSession().getAttribute("user")).getId() + ", nom = " + item.getName());
					s.update(((Utilisateur)request.getSession().getAttribute("user")).getId(), "urlavatar", item.getName());
					File file = new File(destinationDir+dossier,item.getName());
					item.write(file);
				}
				//out.close();
			}
		}catch(FileUploadException ex) {
			log("Error encountered while parsing the request",ex);
		} catch(Exception ex) {
			log("Error encountered while uploading file",ex);
		}
		request.getRequestDispatcher("accueil.jsp").forward(request, response);

	}

}